package org.dromara.comm.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.comm.domain.AsSeekAdviceFrom;
import org.dromara.comm.domain.AsVolunteer;
import org.dromara.comm.mapper.AsSeekAdviceFromMapper;
import org.dromara.comm.mapper.AsVolunteerMapper;
import org.dromara.comm.service.AsSeekAdviceFromService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 咨询管理表业务层
 * @author: 郭伟明
 * @date: 2024-07-30 16:54
 **/
@Service
public class AsSeekAdviceFromServiceImpl extends ServiceImpl<AsSeekAdviceFromMapper, AsSeekAdviceFrom> implements AsSeekAdviceFromService {

    @Autowired
    private AsSeekAdviceFromMapper asSeekAdviceFromMapper;

    @Autowired
    private AsVolunteerMapper asVolunteerMapper;

    /**
     * 发送消息
     * @param id
     */
    @Override
    public AsVolunteer queryVolunteer(Integer id) {
        AsVolunteer volunteer = asVolunteerMapper.selectById(id);
        return volunteer;
    }

    @Override
    public void InsetAsSeekAdviceFromList(AsSeekAdviceFrom asSeekAdviceFrom) {
        AsSeekAdviceFrom advice = new AsSeekAdviceFrom();
        advice.setUserId(asSeekAdviceFrom.getUserId());
        advice.setDetails(asSeekAdviceFrom.getDetails());
        advice.setRId(asSeekAdviceFrom.getRId());
        advice.setCreateTime(new Date());
        asSeekAdviceFromMapper.insert(advice);
    }

    /**
     * 聊天查询
     * @param
     * @return
     */
    @Override
    public List<AsSeekAdviceFrom> selectAsSeekAdviceFromList() {
        List<AsSeekAdviceFrom> asSeekAdviceFroms = asSeekAdviceFromMapper.selectList(null);

        // 将数据按创建时间正序排序
        asSeekAdviceFroms.sort(Comparator.comparing(AsSeekAdviceFrom::getCreateTime));

        // 分组
        List<AsSeekAdviceFrom> group1 = asSeekAdviceFroms.stream()
            .filter(a -> Integer.parseInt(a.getUserId()) % 2 != 0)
            .collect(Collectors.toList());

        List<AsSeekAdviceFrom> group2 = asSeekAdviceFroms.stream()
            .filter(a -> Integer.parseInt(a.getUserId()) % 2 == 0)
            .collect(Collectors.toList());

        // 交叉合并
        List<AsSeekAdviceFrom> result = new ArrayList<>();
        int i = 0, j = 0;
        while (i < group1.size() && j < group2.size()) {
            result.add(group2.get(j++)); // 先添加 group2 的元素
            result.add(group1.get(i++)); // 再添加 group1 的元素
        }

        // 如果其中一个组还有剩余的元素，则添加到结果中
        while (i < group1.size()) {
            result.add(group1.get(i++));
        }

        while (j < group2.size()) {
            result.add(group2.get(j++));
        }
        return result;
    }


}
